﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Exentials.Xoox
{
    internal class XAttributeBase<T>
    {
        private XAttribute _attribute;

        internal XAttributeBase(XElementBase element, string attributeName)
            : this(element, attributeName, default(T))
        { }

        internal XAttributeBase(XElementBase element, int sequence, string attributeName)
            : this(element, attributeName, default(T))
        { }

        internal XAttributeBase(XElementBase element, XName attributeName)
            : this(element, attributeName, default(T))
        { }

        internal XAttributeBase(XElementBase element, string attributeName, T attributeValue)
            : this(element, (XName)attributeName, attributeValue)
        { }

        internal XAttributeBase(XElementBase element, XName attributeName, T attributeValue)
        {
            this._attribute = element.GetXElement().Attribute(attributeName);
            if (this._attribute == null)
            {
                this._attribute = new XAttribute(attributeName, "");
                element.GetXElement().Add(this._attribute);
            }
            if (attributeValue != null)
                _attribute.SetValue(attributeValue);
            
        }

        internal T Value
        {
            get
            {
                return (T)Convert.ChangeType(_attribute.Value, typeof(T), System.Globalization.CultureInfo.InvariantCulture);
            }
            set
            {
                _attribute.SetValue(value);
            }
        }
    }
}
